import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Drawer, Popconfirm } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { FormValueType } from './components/DictItemForm';
import DictItemForm from './components/DictItemForm';
import { list, addDict, updateDict, removeDict } from './service';
import type { TableListItem, TableListPagination } from './data';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');

  try {
    await addDict({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('正在修改');

  try {
    await updateDict({
      ...fields,
    });
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};

const TableList: React.FC = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /** 分布更新窗口的弹窗 */

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  /** 国际化配置 */

  /**
   * 删除节点
   *
   * @param selectedRows
   */

  const handleRemove = async (id: Number) => {
    const hide = message.loading('正在删除');
    try {
      await removeDict({
        key: id,
      });
      hide();
      actionRef.current?.reloadAndRest?.();
      message.success('删除成功，即将刷新');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '类型名称',
      dataIndex: 'dictName',
    },
    {
      title: '唯一编码',
      dataIndex: 'dictCode',
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      hideInSearch: true,
      valueEnum: {
        1: {
          text: '启用',
        },
        0: {
          text: '禁用',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          字典项
        </a>,
        <a
          key="eidt"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </a>,
        <Popconfirm key="delete" title="是否要删除此行？" onConfirm={() => handleRemove(record.id)}>
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const formItemLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };

  return (
    <PageContainer>
      <ProTable<TableListItem, TableListPagination>
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        headerTitle={
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新增类型
          </Button>
        }
        request={async (
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          params,
          sorter,
          filter,
        ) => {
          // console.log(params, sorter, filter);
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          const msg = await list({
            pageNum: params.current,
            pageSize: params.pageSize,
          });
          console.log('msg', msg);
          if (msg.code == 200) {
            return {
              data: msg.data.list,
              // success 请返回 true，
              // 不然 table 会停止解析数据，即使有数据
              success: msg.message,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: msg.data.total,
            };
          } else {
          }
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {createModalVisible ? (
        <ModalForm
          title={currentRow ? '编辑类型' : '新增类型'}
          width="800px"
          layout="horizontal"
          {...formItemLayout}
          visible={createModalVisible}
          onVisibleChange={handleModalVisible}
          initialValues={currentRow || {}}
          onFinish={async (value) => {
            let success;
            if (currentRow) {
              value.id = currentRow.id;
              success = await handleUpdate(value as TableListItem);
            } else {
              success = await handleAdd(value as TableListItem);
            }

            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
        >
          <ProFormText
            rules={[
              {
                required: true,
                message: '请输入字典值',
              },
            ]}
            label="字典值"
            width="md"
            name="dictName"
          />
          <ProFormText
            rules={[
              {
                required: true,
                message: '请输入唯一编码',
              },
            ]}
            label="唯一编码"
            width="md"
            name="dictCode"
          />

          <ProFormTextArea width="md" name="remark" label="备注" />
        </ModalForm>
      ) : null}
      <DictItemForm
        // onSubmit={async (value) => {
        //   const success = await handleUpdate(value, currentRow);
        //   if (success) {
        //     handleUpdateModalVisible(false);
        //     setCurrentRow(undefined);

        //     if (actionRef.current) {
        //       actionRef.current.reload();
        //     }
        //   }
        // }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<TableListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<TableListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
